package com.channel.temperature.collect.ui.fragment

import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.graphics.drawable.ColorDrawable
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.net.Uri
import android.os.Bundle
import android.os.CountDownTimer
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import com.gyf.immersionbar.ktx.immersionBar
import com.hjq.toast.ToastUtils
import com.hjy.bluetooth.HBluetooth
import com.kongzue.dialogx.dialogs.MessageDialog
import com.kongzue.dialogx.dialogs.WaitDialog
import com.kongzue.dialogx.interfaces.OnDialogButtonClickListener
import com.channel.temperature.collect.R
import com.channel.temperature.collect.app.base.BaseFragment
import com.channel.temperature.collect.app.bleupdate.ScanBLEActivity
import com.channel.temperature.collect.app.ext.LiveDataEvent
import com.channel.temperature.collect.app.ext.initBack
import com.channel.temperature.collect.app.ext.mmkv
import com.channel.temperature.collect.app.util.CRC16Utils
import com.channel.temperature.collect.app.util.MyUtil
import com.channel.temperature.collect.data.annotation.ValueKey
import com.channel.temperature.collect.databinding.FragmentSettingBinding
import com.channel.temperature.collect.ui.activity.ColorSettingActivity
import com.channel.temperature.collect.ui.activity.DocWordActivity
import com.channel.temperature.collect.ui.activity.SystemSettingActivity
import com.channel.temperature.collect.ui.viewmodel.SettingModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import me.hgj.mvvmhelper.base.appContext
import me.hgj.mvvmhelper.ext.getAppCode
import me.hgj.mvvmhelper.ext.setOnclickNoRepeat
import me.hgj.mvvmhelper.ext.toStartActivity
import okio.internal.commonAsUtf8ToByteArray


class SettingFragment : BaseFragment<SettingModel, FragmentSettingBinding>() {
    lateinit var mWaitDialog: WaitDialog

    companion object {
        fun newInstance(): SettingFragment {
            val args = Bundle()
            val fragment = SettingFragment()
            fragment.arguments = args
            return fragment
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        mBind.customToolbar.initBack("设置") {
            val messageDialog = MessageDialog(
                "提示", "退出程序？", "确定", "取消"
            ).setButtonOrientation(LinearLayout.HORIZONTAL)
            messageDialog.okButtonClickListener = OnDialogButtonClickListener { dialog, v ->
                lifecycleScope.launch {
                    HBluetooth.getInstance().release()
                    activity?.finish()
                }
                false
            }
            if (this.resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) {
                messageDialog.setMaxWidth(resources.displayMetrics.widthPixels / 2)
            }
            messageDialog.show()
        }
        //0:空闲模式 1：离线模式 3：在线模式
        mViewModel.checkedWorkMode = 0
        mBind.onlineMode.setBackgroundResource(R.drawable.bg_work_mode_unselected)
        mBind.nullMode.setBackgroundResource(R.drawable.bg_work_mode_selected)
        mBind.offlineMode.setBackgroundResource(R.drawable.bg_work_mode_unselected)
        mViewModel.continueClear.value = false
        mViewModel.resetClickType()
    }

    /**
     * 懒加载 第一次获取视图的时候 触发
     */
    override fun lazyLoadData() {

    }

    override fun onRequestSuccess() {
        LiveDataEvent.showTitle.observe(this, Observer {
            if (it) {
                lifecycleScope.launch {
                    mBind.titleTv.visibility = View.VISIBLE
                    mBind.titleTv.text = "当前设备：" + mmkv.getString(
                        ValueKey.CURRENT_DEVICE_NAME, ""
                    ).toString()
                }

            }
        })
        mViewModel.continueClear.observe(this, Observer {
            if (it) {
                lifecycleScope.launch {
                    stopTimeTask()
                    delay(200)
                    countDownTimer = object : CountDownTimer(60000, 1000) {
                        override fun onFinish() {
                            Log.d(SystemSettingActivity.TAG, "==倒计时结束")
                            mWaitDialog?.doDismiss()
                        }

                        override fun onTick(millisUntilFinished: Long) {
                            var second = millisUntilFinished / 1000

                            Log.e(SystemSettingActivity.TAG, "==倒计时" + second + "秒")
                        }
                    }.start()
                    if (HBluetooth.getInstance().isConnected) {
                        HBluetooth.getInstance().sender()?.let { it1 ->
                            mWaitDialog = WaitDialog.show("正在格式化存储区2,请等待..")
                            mWaitDialog.maxWidth =
                                if (appContext.resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) appContext.resources.displayMetrics.widthPixels / 2 else appContext.resources.displayMetrics.widthPixels
                            mViewModel.clickType = 6
                            //Flash1 :430100000000  Flash2:430180000000
                            var cmd = "FF55AA0008" + mViewModel.getAddress() + "430180000000"
                            mViewModel.sendClearAllCMD(
                                cmd + CRC16Utils.checkCRC(
                                    MyUtil.hex2Bytes(
                                        cmd
                                    )
                                )
                            )
                        }
                    } else {
                        ToastUtils.show("请先连接设备后再操作")
                    }
                }
            }
        })
        mViewModel.closeWaitDialog.observe(this, Observer {
            if (it) {
                lifecycleScope.launch {
                    mWaitDialog?.doDismiss()
                }
            }
        })
        mViewModel.showPopupwindow.observe(this, Observer {
            if (it == true) {
                lifecycleScope.launch {
                    mViewModel.showPopupwindow.value = false
                    PopupWindow().apply {
                        //入口参数配置
                        contentView = layoutInflater.inflate(R.layout.pop_edit_device_name, null)
                        width = ViewGroup.LayoutParams.MATCH_PARENT
                        height = ViewGroup.LayoutParams.MATCH_PARENT
                        isFocusable = true
                        val dw = ColorDrawable(0xb0000000.toInt())
                        setBackgroundDrawable(dw)
                        //设置按钮
                        val btnPopupWindow = contentView.findViewById<LinearLayout>(R.id.popLayout)
                        val save = contentView.findViewById<TextView>(R.id.saveTask)
                        val deviceName = contentView.findViewById<EditText>(R.id.deviceET)

                        deviceName.setText(mViewModel.taskDeviceName)
                        save.setOnClickListener {
                            dismiss()
                            if (!deviceName.text.toString().trim().isNullOrEmpty()) {
                                if (HBluetooth.getInstance().isConnected) {
                                    HBluetooth.getInstance().sender()?.let { it1 ->
                                        mViewModel.clickType = 15
                                        var cmd =
                                            "FF55AA0082" + mViewModel.getAddress() + "4502000010300078"

                                        var deviceBytes = get40Bytes()
                                        System.arraycopy(
                                            deviceName.text.toString().commonAsUtf8ToByteArray(),
                                            0,
                                            deviceBytes,
                                            0,
                                            deviceName.text.toString()
                                                .commonAsUtf8ToByteArray().size
                                        )
                                        mViewModel.setedDeviceName = deviceName.text.toString()
                                        cmd =
                                            cmd + MyUtil.bytes2Hex(deviceBytes) + MyUtil.bytes2Hex(
                                                mViewModel.taskCurrentName
                                            ) + MyUtil.bytes2Hex(mViewModel.taskDesc)
                                        mViewModel.sendCommonCMD(
                                            it1, cmd + CRC16Utils.checkCRC(MyUtil.hex2Bytes(cmd))
                                        )
                                    }
                                } else {
                                    ToastUtils.show("请先连接设备后再操作")
                                }
                            } else {
                                ToastUtils.show("设备名称 当前任务名称不能为空")
                            }

                        }
                        btnPopupWindow.setOnClickListener {
                            dismiss()
                        }
                        showAtLocation(contentView, Gravity.CENTER, 0, 0)
                    }
                }

            }
        })
        mViewModel.mAppUpdateEntity.observe(this, Observer {
            if (it != null) {
                lifecycleScope.launch {
                    var currentCode = getAppCode(appContext)
                    if (currentCode < it.build.toInt()) {
                        val messageDialog = MessageDialog.show(
                            "提示",
                            "检测到更新 ：版本：${it.versionShort} \n 更新说明：${it.changelog}",
                            "确定",
                            "取消"
                        )
                        messageDialog.maxWidth =
                            if (appContext.resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) appContext.resources.displayMetrics.widthPixels / 2 else appContext.resources.displayMetrics.widthPixels
                        messageDialog.okButtonClickListener =
                            OnDialogButtonClickListener { dialog, v ->
                                dialog.dismiss()
                                val uri = Uri.parse(it.update_url)
                                val intent = Intent(Intent.ACTION_VIEW, uri)
                                startActivity(intent)
                                true
                            }
                    } else {
                        ToastUtils.show("当前已是最新版本")
                    }
                }
            }
        })
    }

    public fun get40Bytes(): ByteArray {
        var originString = "                                        "//默认40个空格
        var deviceNameByteArray = ByteArray(40)
        var dataBytes = originString.commonAsUtf8ToByteArray()
        System.arraycopy(
            dataBytes, 0, deviceNameByteArray, 0, dataBytes.size
        )
        return deviceNameByteArray
    }

    var countDownTimer: CountDownTimer? = null
    fun restartTimeTask() {
        countDownTimer?.cancel()
        countDownTimer?.start()
    }

    fun stopTimeTask() {
        countDownTimer?.cancel()

    }

    override fun onBindViewClick() {
        //绑定点击事件
        setOnclickNoRepeat(
            mBind.updateBinbtn,
            mBind.setWorkModeLayout,
            mBind.onlineMode,
            mBind.nullMode,
            mBind.offlineMode,
            mBind.pressMode,
            mBind.readTime,
            mBind.checkTime,
            mBind.clearFlash,
            mBind.readTotalSize,
            mBind.setDeviceNameLayout,
            mBind.setChartLineColor,
            mBind.readBattery,
            mBind.checkUpdate,
            mBind.helpDoc
        ) {
            when (it) {

                mBind.updateBinbtn -> {
                    toStartActivity(ScanBLEActivity::class.java)
                }

                mBind.setChartLineColor -> {
                    toStartActivity(ColorSettingActivity::class.java)

                }

                mBind.helpDoc -> {
                    toStartActivity(DocWordActivity::class.java)

                }
                //设置设备名称
                mBind.setDeviceNameLayout -> {
                    mViewModel.queryTaskCMD()
                }
                //读取时间
                mBind.readTime -> {
                    if (HBluetooth.getInstance().isConnected) {
                        HBluetooth.getInstance().sender()?.let { it1 ->
                            mViewModel.clickType = 11
                            var cmd = "FF55AA0004" + mViewModel.getAddress() + "4201"
                            mViewModel.sendCommonCMD(
                                it1, cmd + CRC16Utils.checkCRC(MyUtil.hex2Bytes(cmd))
                            )
                        }
                    } else {
                        ToastUtils.show("请先连接设备后再操作")
                    }
                }
                //读取电池电量
                mBind.readBattery -> {
                    if (HBluetooth.getInstance().isConnected) {
                        HBluetooth.getInstance().sender()?.let { it1 ->
                            mViewModel.clickType = 21
                            var cmd = "FF55AA0003" + mViewModel.getAddress() + "49"
                            mViewModel.sendCommonCMD(
                                it1, cmd + CRC16Utils.checkCRC(MyUtil.hex2Bytes(cmd))
                            )
                        }
                    } else {
                        ToastUtils.show("请先连接设备后再操作")
                    }
                }
                //读取当前存储数量
                mBind.readTotalSize -> {
                    if (HBluetooth.getInstance().isConnected) {
                        HBluetooth.getInstance().sender()?.let { it1 ->
                            mViewModel.clickType = 7
                            var cmd = "FF55AA0003" + mViewModel.getAddress() + "44"
                            mViewModel.sendCommonCMD(
                                it1, cmd + CRC16Utils.checkCRC(MyUtil.hex2Bytes(cmd))
                            )
                        }
                    } else {
                        ToastUtils.show("请先连接设备后再操作")
                    }
                }
                //清空flash
                mBind.clearFlash -> {
                    if (mBind.clearFlashTips.text.toString() == getString(R.string.clear_flash)) {

                        val messageDialog = MessageDialog.show(
                            "提示", "确定${getString(R.string.clear_flash)}？", "确定", "取消"
                        )
                        messageDialog.maxWidth =
                            if (appContext.resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) appContext.resources.displayMetrics.widthPixels / 2 else appContext.resources.displayMetrics.widthPixels
                        messageDialog.okButtonClickListener =
                            OnDialogButtonClickListener { dialog, v ->
                                dialog.dismiss()
                                mViewModel.clearFlashIndex == 0
                                mViewModel.continueClear.value = false
                                countDownTimer = object : CountDownTimer(60000, 1000) {
                                    override fun onFinish() {
                                        Log.d(SystemSettingActivity.TAG, "==倒计时结束")
                                        mWaitDialog?.doDismiss()
                                    }

                                    override fun onTick(millisUntilFinished: Long) {
                                        var second = millisUntilFinished / 1000

                                        Log.e(SystemSettingActivity.TAG, "==倒计时" + second + "秒")
                                    }
                                }.start()
                                if (HBluetooth.getInstance().isConnected) {
                                    HBluetooth.getInstance().sender()?.let { it1 ->
                                        mWaitDialog = WaitDialog.show("正在格式化存储区1,请等待..")
                                        mWaitDialog.maxWidth =
                                            if (appContext.resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) appContext.resources.displayMetrics.widthPixels / 2 else appContext.resources.displayMetrics.widthPixels
                                        mViewModel.clickType = 6
                                        //Flash1 :430100000000  Flash2:430180000000
                                        var cmd =
                                            "FF55AA0008" + mViewModel.getAddress() + "430100000000"
                                        mViewModel.sendClearAllCMD(
                                            cmd + CRC16Utils.checkCRC(
                                                MyUtil.hex2Bytes(
                                                    cmd
                                                )
                                            )
                                        )
                                    }
                                } else {
                                    ToastUtils.show("请先连接设备后再操作")
                                }
                                true
                            }

                    } else {
                        ToastUtils.show("请勿频繁点击")
                    }


                }
                //校时
                mBind.checkTime -> {
                    if (HBluetooth.getInstance().isConnected) {
                        HBluetooth.getInstance().sender()?.let { it1 ->
                            mViewModel.clickType = 31
                            var cmd = "FF55AA0004" + mViewModel.getAddress() + "4201"
                            mViewModel.sendCommonCMD(
                                it1, cmd + CRC16Utils.checkCRC(MyUtil.hex2Bytes(cmd))
                            )
                        }
                    } else {
                        ToastUtils.show("请先连接设备后再操作")
                    }

                }

                mBind.onlineMode -> {
                    mViewModel.checkedWorkMode = 3
                    mBind.onlineMode.setBackgroundResource(R.drawable.bg_work_mode_selected)
                    mBind.nullMode.setBackgroundResource(R.drawable.bg_work_mode_unselected)
                    mBind.offlineMode.setBackgroundResource(R.drawable.bg_work_mode_unselected)
                    mBind.pressMode.setBackgroundResource(R.drawable.bg_work_mode_unselected)
                }

                mBind.nullMode -> {
                    mViewModel.checkedWorkMode = 0
                    mBind.onlineMode.setBackgroundResource(R.drawable.bg_work_mode_unselected)
                    mBind.nullMode.setBackgroundResource(R.drawable.bg_work_mode_selected)
                    mBind.offlineMode.setBackgroundResource(R.drawable.bg_work_mode_unselected)
                    mBind.pressMode.setBackgroundResource(R.drawable.bg_work_mode_unselected)
                }

                mBind.offlineMode -> {
                    mViewModel.checkedWorkMode = 1
                    mBind.onlineMode.setBackgroundResource(R.drawable.bg_work_mode_unselected)
                    mBind.nullMode.setBackgroundResource(R.drawable.bg_work_mode_unselected)
                    mBind.offlineMode.setBackgroundResource(R.drawable.bg_work_mode_selected)
                    mBind.pressMode.setBackgroundResource(R.drawable.bg_work_mode_unselected)
                }

                mBind.pressMode -> {
                    mViewModel.checkedWorkMode = 2
                    mBind.pressMode.setBackgroundResource(R.drawable.bg_work_mode_selected)
                    mBind.onlineMode.setBackgroundResource(R.drawable.bg_work_mode_unselected)
                    mBind.nullMode.setBackgroundResource(R.drawable.bg_work_mode_unselected)
                    mBind.offlineMode.setBackgroundResource(R.drawable.bg_work_mode_unselected)
                }
                //查询设备系统参数后再设置
                mBind.setWorkModeLayout -> {
                    if (HBluetooth.getInstance().isConnected) {
                        HBluetooth.getInstance().sender()?.let { it1 ->
                            mViewModel.clickType = 9
                            var cmd = "FF55AA000A" + mViewModel.getAddress() + "45010000000000C8"
                            mViewModel.sendCommonCMD(
                                it1, cmd + CRC16Utils.checkCRC(MyUtil.hex2Bytes(cmd))
                            )
                        }
                    } else {
                        ToastUtils.show("请先连接设备后再操作")
                    }
                }

                mBind.checkUpdate -> {
                    lifecycleScope.launch {
                        if (isNetworkAvailable(mActivity)) {
                            mViewModel.checkFirUpdate(false, false)
                        } else {
                            ToastUtils.show("当前没有网络")
                        }

                    }

                }
            }
        }
    }

    fun isNetworkAvailable(appCompatActivity: AppCompatActivity): Boolean {
        val context = appCompatActivity.applicationContext
        val connectivityManager =
            context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        if (connectivityManager == null) {
            return false
        } else {
            val networkInfo = connectivityManager.allNetworkInfo
            if (networkInfo != null && networkInfo.size > 0) {
                for (i in networkInfo.indices) {
                    if (networkInfo[i].state == NetworkInfo.State.CONNECTED) {
                        return true
                    }
                }
            }
        }
        return false
    }

    private fun initListener() {
        HBluetooth.getInstance().setReceiver { dataInputStream, result -> //设备发过来的数据将在这里出现
            mViewModel.handleBLEResult(result)
        }
    }

    override fun onResume() {
        super.onResume()
        initListener()
        immersionBar {
            titleBar(mBind.customToolbar)
        }
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        mViewModel.showPopupwindow.value = false
    }
}